//
//  ATOnline.m
//  Yami
//
//  Created by 敖然 on 15/12/15.
//  Copyright © 2015年 AT. All rights reserved.
//

#import "ATOnline.h"

NSString * const ATOnlineChangeNotification = @"ATOnlineChangeNotification";
@interface ATOnline ()
@property (nonatomic, assign) BOOL online;
@end

static NSString *ATOnlineKey = @"ATOnlineApiOnlineKey";
@implementation ATOnline

static ATOnline *_instance;
+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
        _instance.online = [[NSUserDefaults standardUserDefaults] boolForKey:ATOnlineKey];
        
        // 自动检查更新
        [self performSelector:@selector(checkUpdate) withObject:nil afterDelay:0.5];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkUpdate) name:UIApplicationDidBecomeActiveNotification object:nil];
    });
    return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}
+ (BOOL)isOnline {
#if DEBUG
    return [[self shareInstance] online];
#endif
    return YES;
}
+ (void)switchEnvironment:(BOOL)isOnline {
    [ATLocal loginOut];
    [[self shareInstance] setOnline:isOnline];
    [[UIApplication sharedApplication].delegate application:[UIApplication sharedApplication] didFinishLaunchingWithOptions:nil];
}

- (void)setOnline:(BOOL)online {
    _online = online;
    
    [[NSUserDefaults standardUserDefaults] setBool:_online forKey:ATOnlineKey];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:ATOnlineChangeNotification object:@(_online)];
}

+ (NSString *)baseURL {
    NSString *_baseURL;
    if ([ATOnline isOnline]) {
        _baseURL = @"http://47.96.146.113:8081/tp/";
    }
    else {
        _baseURL = @"http://47.96.146.113:8082/tp/";
    }
    return _baseURL;
}

+ (BOOL)isReviewing {
    return ![ATLocal simple].readyForSale
    && (![ATLocal user].userId || [[ATLocal user].userId isEqualToString:@"754585"]);
}

+ (void)checkUpdate {
#if defined(ADHOC) || defined(DEBUG)
    static NSTimeInterval lastTime = 0;
    if ([NSDate date].timeIntervalSince1970 - lastTime <= 300) {
        return;
    }
    lastTime = [NSDate date].timeIntervalSince1970;
    [ATHttpTool GET:[NSString stringWithFormat:@"http://api.fir.im/apps/latest/%@", [UIApplication sharedApplication].appBundleID] params:@{@"api_token" : @"9938de116fd1a79f282e7cfef7d888d7", @"type" : @"ios"} success:^(NSURLSessionDataTask *task, id responseObject) {
        @try {
            if ([responseObject[@"version"] longLongValue] > [UIApplication sharedApplication].appBuildVersion.longLongValue) {
                [ATAlertView showTitle:[NSString stringWithFormat:@"发现新版本ver%@", responseObject[@"versionShort"]]
                               message:[NSString stringWithFormat:@"\r\nApp升级啦(BuildVer %@), 赶紧更新体验吧~\r\n%@", responseObject[@"version"], SafeDicObj(responseObject[@"changelog"])] normalButtons:@[@"取消"]
                      highlightButtons:@[@"立即更新"]
                            completion:^(NSInteger index, NSString *buttonTitle) {
                                if (index <= 0) {
                                    return;
                                }
                                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"itms-services://?action=download-manifest&url=%@", [responseObject[@"install_url"] stringByURLEncode]]]];
                            }];
            }
        } @catch (NSException *exception) {
        }
    } failure:nil];
#endif
}
@end
